package personal.wang.manager;

import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import personal.wang.enm.TaskStatus;
import personal.wang.job.TestPointV2;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * describe: 从配置文件中读取 TestPoint 节点信息，然后然后序列化，并发送给 Boss，
 * Boss 负责分发任务。
 */
public class RecordGeneratorManager {
    private static Logger logger = LoggerFactory.getLogger(RecordGeneratorManager.class);
    private ReentrantLock lock = new ReentrantLock();
    private Map<String , TestPointV2> testPointV2s = new ConcurrentHashMap<>();
    private CuratorFramework curatorFramework ;
    public RecordGeneratorManager(){}
    public RecordGeneratorManager(Map<String, TestPointV2> testPointV2s, CuratorFramework curatorFramework) {
        this.testPointV2s = testPointV2s;
        this.curatorFramework = curatorFramework;
    }

    public void putTestPoint(TestPointV2 testPointV2){
        testPointV2s.put(testPointV2.getTestPointInfo().getName() , testPointV2);
    }
    public TestPointV2 getTestPoint(TestPointV2 testPointV2){
        return testPointV2s.get(testPointV2.getTestPointInfo().getName());
    }


    public void loadTask(CuratorFramework curatorFramework) {
        logger.info("load tasks");
    }

    public void clearTask(CuratorFramework curatorFramework) {
        logger.info("clean tasks");
    }

    public void ack(String host, TaskStatus taskStatus) {
        lock.lock();
        try{
            TestPointV2 testPointV2 = testPointV2s.get(host);
            testPointV2.setTaskStatus(taskStatus);
        }catch (Exception e){
            logger.error("{}" , e.getMessage());
        }finally {
            lock.unlock();
        }
    }

    public String getTaskInfo() {
        String collect = testPointV2s.values().stream().map(x -> x.getTestPointInfo().getName() + "  " + x.getTaskStatus()).collect(Collectors.joining("\n"));
        return collect ;
    }
}
